# server.py
from flask import Flask, request, jsonify
from flask_cors import CORS
import threading
import queue

app = Flask(__name__)
CORS(app)  # 允许跨域请求

# 使用队列存储打印任务
print_queue = queue.Queue()

@app.route('/register_computer', methods=['POST'])
def register_computer():
    """电脑端注册接口"""
    data = request.json
    computer_id = data.get('computer_id')
    # 这里可以添加验证逻辑
    return jsonify({'status': 'success', 'message': 'Computer registered'})

@app.route('/send_print_task', methods=['POST'])
def send_print_task():
    """手机端发送打印任务接口"""
    data = request.json
    task = {
        'computer_id': data.get('computer_id'),
        'content': data.get('content'),
        'timestamp': data.get('timestamp')
    }
    print_queue.put(task)
    return jsonify({'status': 'success', 'message': 'Print task received'})

@app.route('/get_print_task', methods=['GET'])
def get_print_task():
    """电脑端获取打印任务接口"""
    computer_id = request.args.get('computer_id')
    try:
        task = print_queue.get_nowait()
        if task['computer_id'] == computer_id:
            return jsonify({'status': 'success', 'data': task})
        else:
            # 如果不是该电脑的任务，放回队列
            print_queue.put(task)
            return jsonify({'status': 'no_task'})
    except queue.Empty:
        return jsonify({'status': 'no_task'})

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=6666, debug=True)